<template>
    <div style="position: absolute;top:0;bottom: 0;" >
        <!--        导航栏-->
        <wxc-minibar background-color="white"
                     text-color="black">
            <template slot="middle">
                <text class="topBarFont">功能页</text>
            </template>
        </wxc-minibar>
        <!--        主体内容-->
        <div class="mainContent">
            <!--            乐谱显示框-->
            <div class="musicScoreContainer" :style="styles.musicScoreContainer">
                <div class="musicScoreTip" :style="styles.musicScoreTip">
                    <image class="tipIcon" :src="img.musicScoreUrl"></image>
                    <text class="musicScoreIcon" style="position:absolute;left: 60px;">乐谱展示</text>
                </div>
                <div style="align-items: center">
                    <text style="margin-top:85px;font-size:25px;font-weight:900">暂无乐谱</text>
                </div>
            </div>
            <div style="flex-direction:row;margin-left: 5px">
                <!--            音符输入和问题输入框-->
                <div style="width:290px;" :style="styles.musicInputAndQuestion"  >
                    <div :style="styles.musicScoreTip" style="border-style:solid;border-width:1px;border-color:#BBBBBB;justify-content: center">
                        <image class="tipIcon" :src="img.musicFlagUrl"></image>
                        <text class="resultIcon" style="position:absolute;left: 60px;">音符输入</text>
                        <text style="position:absolute;font-weight: 900;font-size: 40px;right: 10px"
                              @click="popMusicFlagInput">
                            +
                        </text>
                    </div>
                    <list ref="musicFlagScroller" style="border-style:solid;border-width:1px;border-color:#BBBBBB;">
                        <cell v-if="musicFlagList.length>0" @click="switchMusicFlagInput(index)"
                              v-for="(flag,index) in musicFlagList" :key="flag.uuid">
                            <music-flag-input :key="flag.uuid" @on-delete="musicFlagList.splice(index,1)"
                                              :x-value.sync="flag.xValue"
                                              :y-value.sync="flag.yValue"
                                              :is-clicked="flag.isClicked"></music-flag-input>
                        </cell>
                        <cell style="align-items: center" v-if="musicFlagList.length===0">
                            <text style="margin-top:125px;font-size:25px;font-weight:900">请点击右上+号添加音符</text>
                        </cell>
                    </list>
                </div>
                <div style="width:450px;" :style="styles.musicInputAndQuestion" >
                    <div  :style="styles.musicScoreTip"  style="border-style:solid;border-width:1px;border-color:#BBBBBB;height:40wx;justify-content: center">
                        <image class="tipIcon" :src="img.relevanceUrl"></image>
                        <text class="resultIcon" style="position:absolute;left: 60px;">问题输入</text>
                        <text style="position:absolute;font-weight: 900;font-size: 40px;right: 10px"
                              @click="popRelationMenu">
                            +
                        </text>
                        <wxc-popover ref="wxc-popover"
                                     :buttons="btns"
                                     :position="popoverPosition"
                                     @wxcPopoverButtonClicked="popoverButtonClicked"
                                     :arrowPosition="popoverArrowPosition"></wxc-popover>
                    </div>
                    <list ref="musicFlagScroller"
                          style="border-style:solid;border-width:1px;border-color:#BBBBBB;">
                        <cell v-if="musicQuestionList.length>0" v-for="(item,index) in musicQuestionList"
                              :key="item.uuid">
                            <music-interval-input :uuid="item.uuid"
                                                  @on-delete="handleMusicQuestionDelete(item.uuid,index)"
                                                  @on-finish="handleIntervalInputFinished" :order-number="index+1"
                                                  @pushFirstArg="handlePushArg" @pushLastArg="handlePushArg"
                                                  :key="item.uuid" v-if="item.type==='interval'"></music-interval-input>
                            <music-get-by-interval-input
                                    :uuid="item.uuid"
                                    :order-number="index+1"
                                    :key="item.uuid"
                                    @on-delete="handleMusicQuestionDelete(item.uuid,index)"
                                    @on-finish="handleGetByIntervalFinished"
                                    @pushFirstArg="handlePushArg"
                                    v-if="item.type==='getByInterval'"
                            ></music-get-by-interval-input>
                            <music-chord-triad-input
                                    :uuid="item.uuid"
                                    :order-number="index+1"
                                    v-if="item.type==='getTriad'"
                                    :key="item.uuid"
                                    @on-delete="handleMusicQuestionDelete(item.uuid,index)"
                                    @on-finish="handleTriadFinished"
                                    @pushFirstArg="handlePushArg"
                                    @pushSecondArg="handlePushArg"
                                    @pushThirdArg="handlePushArg"></music-chord-triad-input>
                            <music-chord-seventh-input
                                    v-if="item.type==='getSeventh'"
                                    :uuid="item.uuid"
                                    :order-number="index+1"
                                    :key="item.uuid"
                                    @on-delete="handleMusicQuestionDelete(item.uuid,index)"
                                    @on-finish="handleSeventhFinished"
                                    @pushFirstArg="handlePushArg"
                                    @pushSecondArg="handlePushArg"
                                    @pushThirdArg="handlePushArg"
                                    @pushFourthArg="handlePushArg"
                            ></music-chord-seventh-input>
                        </cell>
                        <cell style="align-items: center" v-if="musicQuestionList.length===0">
                            <text style="margin-top:125px;font-size:25px;font-weight:900">暂无问题,请点击右上角+号添加</text>
                        </cell>
<!--                        <cell>-->
<!--                            <music-chord-triad-input-->
<!--                                    @on-finish="handleTriadFinished"-->
<!--                                    @pushFirstArg="handlePushArg"-->
<!--                                    @pushSecondArg="handlePushArg"-->
<!--                                    @pushThirdArg="handlePushArg"></music-chord-triad-input>-->
<!--                            <music-chord-seventh-input-->
<!--                                    @on-finish="handleSeventhFinished"-->
<!--                                    @pushFirstArg="handlePushArg"-->
<!--                                    @pushSecondArg="handlePushArg"-->
<!--                                    @pushThirdArg="handlePushArg"-->
<!--                                    @pushFourthArg="handlePushArg"-->
<!--                            ></music-chord-seventh-input>-->
<!--                            &lt;!&ndash;                                                    <music-get-by-interval-input   @on-finish="handleGetByIntervalFinished" @pushFirstArg="handlePushArg" > </music-get-by-interval-input>&ndash;&gt;-->
<!--                        </cell>-->
                    </list>
                </div>
            </div>
            <!--            结果显示框-->
            <div class="resultContainer" :style="styles.resultContainer">
                <div class="resultTip" :style="styles.musicScoreTip">
                    <image class="tipIcon" :src="img.answerUrl"></image>
                    <text class="resultIcon" style="position:absolute;left: 60px;">答案输出</text>
                </div>
                <list  style="width:740px;margin-left:5px;border-style:solid;border-width:1px;border-color:#BBBBBB;justify-content: center">
                    <cell style="align-items: center" v-if="musicResultList.length===0">
                        <music-get-by-interval-show :result="packageData.temp"></music-get-by-interval-show>
                        <text style="margin-top:125px;font-size:25px;font-weight:900">暂无答案结果,请添加问题输入后查看</text>
                    </cell>
                    <cell v-if="musicResultList.length>0" v-for="(item,index) in musicResultList" :key="item.uuid">
                        <music-result-show v-if="item.type==='interval'" :interval-result="item"
                                           :key="item.uuid"></music-result-show>
                        <music-result-get-by-interval-show v-if="item.type==='getByInterval'" :result="item"
                                                           :key="item.uuid"></music-result-get-by-interval-show>
                        <music-result-get-seventh-show v-if="item.type==='getSeventhChord'"
                        :result="item" :key="item.uuid" ></music-result-get-seventh-show>
                        <music-result-get-triad-show v-if="item.type==='getTriad'"
                                                       :result="item" :key="item.uuid" ></music-result-get-triad-show>
                    </cell>
                </list>
            </div>
        </div>
        <!--            钢琴键盘-->
        <div style="margin-left:5px;position:absolute;bottom:0;left:0;right:0;background: whitesmoke;flex-direction: row">
            <piano-key :offset-left="key.whiteOffset.left.replace('px','')" @pressed="handleKeyInput"
                       :x-value.sync="key.xValue" :y-value.sync="key.yValue"
                       class="whiteKey" v-for="key in packageData.pianoKeyList.filter(item=>!item.offset)"
                       :key="index"></piano-key>
            <piano-key :offset-left="key.offset.left.replace('px','')" @pressed="handleKeyInput"
                       :x-value.sync="key.xValue" :y-value.sync="key.yValue" type="black"
                       class="blackKey" :style="key.offset"
                       v-for="key in  packageData.pianoKeyList.filter(item=>item.offset)"
                       :key="index"></piano-key>
        </div>
        <text @click="handlePianoKeySwitch('add')" :style="styles.keySubAddBtn"
              style="position:absolute;left:5px;width:60px;height:60px;background-color: whitesmoke;border-radius: 10px;border-color: black;border-width: 3px;border-style: solid;font-size: 70px;font-weight: 900;text-align: center;padding-top: -15px">+
        </text>
        <text @click="handlePianoKeySwitch('sub')" :style="styles.keySubAddBtn"
              style="position:absolute;right:0;width:60px;height:60px;background-color: whitesmoke;border-radius: 10px;border-color: black;border-width: 3px;border-style: solid;font-size: 70px;font-weight: 900;text-align: center;padding-top: -15px">-
        </text>
    </div>
</template>

<script>
    /**
     * 功能页
     */
    import {WxcMinibar, WxcPopover} from 'weex-ui';
    import Nat from 'natjs'
    import MusicFlagInput from "./components/music-flag-input";
    import PianoKey from "./components/piano-key";
    import {getDeviceHeight, getFormatHeightPX, toast} from "../../util/common";
    import MusicIntervalInput from "./components/music-interval-input";
    import MusicResultShow from "./components/music-result-show";
    import {getImagePath} from "../../util/path-util";
    import {getMusicFlagByMusicNameYValue, getMusicFlagByXYValue, getSeventh, getTriad} from "../../util/compute";
    import MusicGetByIntervalInput from "./components/music-get-by-interval-input";
    import MusicGetByIntervalShow from "./components/music-result-get-by-interval-show";
    import MusicResultGetByIntervalShow from "./components/music-result-get-by-interval-show";
    import MusicChordTriadInput from "./components/music-chord-triad-input";
    import MusicChordSeventhInput from "./components/music-chord-seventh-input";
    import MusicResultGetSeventhShow from "./components/music-result-get-seventh-show";
    import MusicResultGetTriadShow from "./components/music-result-get-triad-show";

    export default {
        name: "function-module",
        components: {
            MusicResultGetTriadShow,
            MusicResultGetSeventhShow,
            MusicChordSeventhInput,
            MusicChordTriadInput,
            MusicResultGetByIntervalShow,
            MusicGetByIntervalShow,
            MusicGetByIntervalInput,
            MusicResultShow, MusicIntervalInput, PianoKey, MusicFlagInput, WxcMinibar, WxcPopover
        },
        data() {
            return {
                packageData: {
                    temp: null,
                    pianoKeyList: [
                        {"xValue": "c", "yValue": "60", whiteOffset: {'left': '5px'}},
                        {"xValue": "c", "yValue": "61", offset: {'left': '70px'}},
                        {"xValue": "d", "yValue": "62", whiteOffset: {'left': '110px'}},
                        {"xValue": "d", "yValue": "63", offset: {'left': '180px'}},
                        {"xValue": "e", "yValue": "64", whiteOffset: {'left': '215px'}},
                        {"xValue": "f", "yValue": "65", whiteOffset: {'left': '320px'}},
                        {"xValue": "f", "yValue": "66", offset: {'left': '390px'}},
                        {"xValue": "g", "yValue": "67", whiteOffset: {'left': '425px'}},
                        {"xValue": "g", "yValue": "68", offset: {'left': '500px'}},
                        {"xValue": "a", "yValue": "69", whiteOffset: {'left': '530px'}},
                        {"xValue": "a", "yValue": "70", offset: {'left': '610px'}},
                        {"xValue": "b", "yValue": "71", whiteOffset: {'left': '615px'}},
                    ]
                },
                img: {
                    musicScoreUrl: getImagePath('music_score'),
                    musicFlagUrl: getImagePath('music_flag'),
                    relevanceUrl: getImagePath('relevance'),
                    answerUrl: getImagePath('answer')
                },
                btns: [
                    {
                        text: '两个音之间的音程',
                        key: 'interval'
                    }, {
                        text: '已知1音与音程求2音',
                        key: 'getKeyByInterval'
                    },
                    {
                        text: '已知三个音求三和弦',
                        key: 'getTriad'
                    },
                    {
                        text: '已知四个音求七和弦',
                        key: 'getSeventh'
                    },
                ],
                popoverPosition: {x: -33, y: 380},
                popoverArrowPosition: {pos: 'right'},
                layoutParams: {
                    fullScreen: `position:absolute;top:0;bottom:0;left:0;right:0;`
                },
                musicFlagList: [],
                musicQuestionList: [],
                musicResultList: [],
                currentMusicFlag: '',
                consoleLog: '',
                styles:{
                    musicScoreContainer:{
                        height:getDeviceHeight(0.2)
                    },
                    musicScoreTip:{
                        height:getDeviceHeight(0.05)
                    },
                    musicInputAndQuestion:{
                        height:getDeviceHeight(0.25)
                    },
                    resultContainer:{
                        height:getDeviceHeight(0.252),
                        'border-width':'1px',
                        'border-style':'solid',
                        'border-color':'black'
                    },
                    keySubAddBtn:{
                        bottom:getFormatHeightPX(230)
                    }
                }
            }
        },
        mounted() {
            // let width = this.$getConfig().env.deviceWidth;
            // let height = this.$getConfig().env.deviceHeight;
            // toast(width + '--' + height)
//             let h = getDeviceHeight();
// toast(getFormatHeightPX(60))
            // toast(h)
            },
        methods: {
            //当三和弦问题填写完毕后的回调
            handleTriadFinished(chord){
                if(!chord||!chord.result){toast('输入的三个音无法计算三和弦!建议更换后再试')
                    return false;}
                // 判断是否结果已经存在
                let exist = this.getQuestionResult(chord.uuid);
                if (exist) {
                    this.$set(this.musicResultList, exist.index, {...chord, type: 'getTriad'})
                } else {
                    //放入一个答案输出
                    this.musicResultList.push({...chord, type: 'getTriad'})
                }
            },
            //当七和弦问题填写完毕后的回调
            handleSeventhFinished(chord){
                if(!chord||!chord.result){toast('输入的四个音无法计算七和弦!建议更换后再试')
                    return false;}
                // 判断是否结果已经存在
                let exist = this.getQuestionResult(chord.uuid);
                if (exist) {
                    this.$set(this.musicResultList, exist.index, {...chord, type: 'getSeventhChord'})
                } else {
                    //放入一个答案输出
                    this.musicResultList.push({...chord, type: 'getSeventhChord'})
                }
            },
            //当已知一音和音程问题填写完毕后的回调
            handleGetByIntervalFinished(interval) {
                if (!interval || !interval.result) {
                    return false
                }
                // 判断是否结果已经存在
                let exist = this.getQuestionResult(interval.uuid);
                if (exist) {
                    this.$set(this.musicResultList, exist.index, {...interval, type: 'getByInterval'})
                } else {
                    //放入一个答案输出
                    this.musicResultList.push({...interval, type: 'getByInterval'})
                }
            },
            //增/减钢琴键的八度
            handlePianoKeySwitch(type) {
                // this.show();
                let success = true;
                // toast(this.packageData)
                let copy = JSON.parse(JSON.stringify(this.packageData.pianoKeyList))
                switch (type) {
                    case 'sub':
                        this.packageData.pianoKeyList.forEach((key, index) => {
                            let yValue = +key.yValue - 12;
                            let flag = getMusicFlagByMusicNameYValue(key.xValue, yValue.toString());
                            if (!flag) {
                                success = false;
                            } else {
                                copy[index].xValue = flag.musicName;
                                copy[index].yValue = flag.yValue
                            }
                        })
                        break;
                    case 'add':
                        this.packageData.pianoKeyList.forEach((key, index) => {
                            let yValue = +key.yValue + 12;
                            let flag = getMusicFlagByMusicNameYValue(key.xValue, yValue.toString());
                            if (!flag) {
                                success = false;
                            } else {
                                copy[index].xValue = flag.musicName;
                                copy[index].yValue = flag.yValue
                            }
                        })
                        break;
                }
                if (success) {
                    // this.pianoKeyList  = copy;
                    this.$set(this.packageData, 'pianoKeyList', copy);
                    // toast(copy)
                }
            },
            //当问题删除时回调
            handleMusicQuestionDelete(uuid, index) {
                //如果答案中存在该问题结果,也要删除对应答案
                let result = this.getQuestionResult(uuid);
                if (result) {
                    this.musicResultList.splice(result.index, 1);
                }
                this.musicQuestionList.splice(index, 1);
                this.refreshResultList();
            },
            //刷新结果框
            refreshResultList() {
                this.musicResultList.forEach((item, idx) => {
                    this.musicQuestionList.forEach((question, index) => {
                        if (item.uuid === question.uuid) {
                            this.$set(this.musicResultList, idx, {...item, index: index + 1})
                        }
                    })
                })
            },
            //音程音输入事件
            handlePushArg(cb) {
                cb(this.currentMusicFlag, result => {
                    //当两个音都输入完成后，走该回调事件
                });
            },
            //查找答案输出列表中是否存在对应uuid的问题答案
            getQuestionResult(uuid) {
                let res = null;
                this.musicResultList.find((item, index) => {
                    if (item.uuid === uuid) {
                        res = {index, item}
                    }
                })
                return res;
            },
            //当音程问题两个音都选择后的回调
            handleIntervalInputFinished(res) {
                if (!res.result) {
                        toast('你输入的两个音无法计算音程,建议更换音后再试');
                } else {
                    //判断是否结果已经存在
                    let exist = this.getQuestionResult(res.uuid);
                    if (exist) {
                        this.$set(this.musicResultList, exist.index, {...res, type: 'interval'})
                    } else {
                        //放入一个答案输出
                        this.musicResultList.push({...res, type: 'interval'})
                    }
                }
            },
            switchMusicFlagInput(index) {
                this.musicFlagList.forEach((item, index1) => {
                    index === index1 ? (() => {
                        item.isClicked = true;
                        this.currentMusicFlag = item;
                    })() : item.isClicked = false
                })
            },
            popMusicFlagInput() {
                this.musicFlagList.push({
                    uuid: new Date().getTime().toString(),
                    xValue: '60',
                    yValue: '60',
                    isClicked: false
                })
            },
            //弹出问题输入类型选择菜单
            popRelationMenu() {
                this.$refs['wxc-popover'].wxcPopoverShow();
            },
            //当类型选择后的回调事件
            popoverButtonClicked(obj) {
                switch (obj.index.toString()) {
                    case '0':
                        this.musicQuestionList.push({
                            uuid: new Date().getTime().toString(),
                            'type': 'interval',
                            firstArg: null,
                            lastArg: null
                        })
                        break;
                    //已知1音与音程求2音
                    case '1':
                        this.musicQuestionList.push({
                            uuid: new Date().getTime().toString(),
                            'type': 'getByInterval',
                        })
                        break;
                    //已知三个音求三和弦
                    case '2':
                        this.musicQuestionList.push({
                            uuid: new Date().getTime().toString(),
                            'type': 'getTriad'
                        })
                        break;
                    //已知四个音求七和弦
                    case '3':
                        this.musicQuestionList.push({
                            uuid: new Date().getTime().toString(),
                            'type': 'getSeventh'
                        })
                        break;
                }
            },
            handleKeyInput(info) {
                this.currentMusicFlag.xValue = info.xValue;
                this.currentMusicFlag.yValue = info.yValue;
            }

        }
    }
</script>

<style scoped>
    .mainContent {
        align-content: center;
    }

    .musicScoreContainer {
        /*height: 170wx;*/
    }

    .musicScoreTip {
        width: 740px;
        /*height: 40wx;*/
        align-self: center;
        border-style: solid;
        border-width: 1px;
        border-color: #BBBBBB;
        justify-content: center;
    }

    .musicScoreIcon {
        font-size: 28px;
        margin-left: 10px;
    }

    .tipIcon {
        position: absolute;
        left: 15px;
        width: 40px;
        height: 40px;
    }


    .resultContainer {
    }

    .resultTip {
        width: 740px;
        align-self: center;
        border-style: solid;
        border-width: 1px;
        border-color: #BBBBBB;
        justify-content: center;
    }

    .resultIcon {
        font-size: 28px;
        margin-left: 10px;
    }


    .topBarFont {
        font-size: 36px;
        font-weight: 900;
    }

    .whiteKey {
        flex: 1;
        border-width: 2px;
        border-style: solid;
        border-color: #999;
        background-color: rgb(238, 238, 238);
    }

    .blackKey {
        position: absolute;
        border-width: 2px;
        border-style: solid;
        border-color: #999;
        background-color: rgb(95, 89, 89);
        width: 68px
    }

    .whiteKey:active {
        background-color: rgba(122, 125, 125, 0.76);
    }

    .blackKey:active {
        background-color: rgba(122, 125, 125, 1);
    }
</style>
